package cz.schovjan.proj.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import cz.schovjan.proj.dao.IBandDao;
import cz.schovjan.proj.dao.IConcertDao;
import cz.schovjan.proj.dto.Band;
import cz.schovjan.proj.dto.Concert;
import cz.schovjan.proj.entity.BandEntity;
import cz.schovjan.proj.entity.ConcertEntity;
import cz.schovjan.proj.service.IConcert;

/**
 * Implementace rozhrani IConcert pro praci s koncerty.
 * @author schovjan
 *
 */
@Transactional
public class ConcertImpl implements IConcert {

	@Autowired
	private IConcertDao concertDao;
	
	@Autowired
	private IBandDao bandDao;
	
	
	@Override
	public void add(String place, Date dateTime, String description) {
		ConcertEntity ce = new ConcertEntity();
		ce.setPlace(place);
		ce.setDateTime(dateTime);
		ce.setDescription(description);
		
		concertDao.add(ce);
	}

	
	@Override
	public List<Concert> findOtherConcerts(Integer id) {
		List<Concert> result = new ArrayList<Concert>();
		List<ConcertEntity> ceAll = concertDao.findAll();
		BandEntity band = bandDao.find(id);
		
		for (ConcertEntity me : band.getConcerts()) {
			ceAll.remove(me);
		}
		for (ConcertEntity ce : ceAll) {
			result.add(loadConcert(ce));
		}
		
		return result;
	}
	
	
	/**
	 * Vrati nasetovany koncert.
	 * @param ce
	 * @return
	 */
	private Concert loadConcert(ConcertEntity ce) {
		
		if (ce==null) {
			return null;
		}
		
		Concert c = new Concert();
		c.setId(ce.getId());
		c.setPlace(ce.getPlace());
		c.setDateTime(ce.getDateTime());
		c.setDescription(ce.getDescription());
		
		List<Band> bands = new ArrayList<Band>();
		Band b;
		for (BandEntity be : ce.getBands()) {
			b = new Band();
			b.setId(be.getId());
			b.setName(be.getName());
			b.setDescription(be.getDescription());
			b.setEmail(be.getEmail());
			b.setCreation(be.getCreation());
			b.setBreakup(be.getBreakup());
			
			bands.add(b);
		}
		
		c.setBands(bands);
		
		return c;
	}

	
	@Override
	public Concert find(Integer id) {
		ConcertEntity ce = concertDao.find(id);

		return loadConcert(ce);
	}
	
	
	@Override
	public void save(Integer id, String place, Date dateTime, String description) {
		ConcertEntity ce = concertDao.find(id);
		ce.setPlace(place);
		ce.setDateTime(dateTime);
		ce.setDescription(description);
	}
	
}
